package com.yimi.policyservice.controller;


import cn.hutool.core.lang.UUID;
import com.github.pagehelper.Page;
import com.yimi.policyservice.common.annotation.Auth;
import com.yimi.policyservice.common.constant.GloabConstant;
import com.yimi.policyservice.common.constant.MsgConstant;
import com.yimi.policyservice.common.constant.RedisConstant;
import com.yimi.policyservice.common.expetion.ApiException;
import com.yimi.policyservice.dto.PageDto;
import com.yimi.policyservice.dto.policyaddr.IdsBean;
import com.yimi.policyservice.dto.user.*;
import com.yimi.policyservice.entity.base.system.SysOrganization;
import com.yimi.policyservice.entity.base.system.SysUser;
import com.yimi.policyservice.service.SmsCodeService;
import com.yimi.policyservice.service.UserService;
import com.yimi.policyservice.utils.TokenUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jack
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    private static final String DEFAULT_PASSWORD = "123456" ;
    @Autowired
    private UserService  userService ;

    @Autowired
    private SmsCodeService smsCodeService ;

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;

   ;

    @Value("${upload.path}")
    private String path;

    @Value("${upload.url}")
    private String url;

    /**
     * 用户注册
     * @return
     * @author jack
     */
    @RequestMapping(value = "",method = RequestMethod.POST)
    public SysUser create(@RequestBody User4Create bean){
        if(StringUtils.isBlank(bean.getLoginName())){
            bean.setLoginName(bean.getTelephone());
        }
        if(StringUtils.isBlank(bean.getPassword())){
            bean.setPassword(DEFAULT_PASSWORD);
        }
        bean.setStatus("0");
        userService.checkLoginName(bean.getLoginName());
       return userService.regist(bean);
    }

    @RequestMapping("login")
    public UserLogin4Get login(@RequestBody User4Login bean){
        return userService.login(bean);
    }

    /**
     * 校验短信验证码
     * 获取一个修改密码的临时token
     * @param code
     * @param phone
     * @return
     */
    @RequestMapping(value = "checksms" ,method = RequestMethod.GET)
    public Map chekUpdatePwdSmsCode(String code,String phone){
       boolean check =  smsCodeService.verfiy(phone,code);
       if(!check){
           throw  new ApiException(400,MsgConstant.SMS_CODE_ERROR);
       }
       String key = UUID.randomUUID().toString();
       stringRedisTemplate.opsForValue().set(String.format(RedisConstant.SMS_TOKEN,key),phone);
       Map<String,String> res = new HashMap<>();
       res.put("token",key);
       return  res ;
    }

    /**
     * 忘记密码
     * 修改密码
     */
    @RequestMapping(value = "passwordbysms", method = RequestMethod.PUT)
    public void updatePasswordBySms(@RequestBody Password4Put bean){
        userService.updatePasswordBySmsCode(bean);
    }

    /**
     * 用户中心
     * 修改密码
     */
    @RequestMapping(value = "password", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @Auth
    public void updatePassword(@RequestBody Password4Put bean, HttpServletRequest request){
        String userId = TokenUtil.parseJWT(request.getHeader(GloabConstant.tokenName));
        userService.updatePasswordByOldPassword(userId,bean);
    }

    @RequestMapping(value = "phone", method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @Auth
    public void updateUserMobile(@RequestParam String phone ,@RequestParam String code){
        if(smsCodeService.verfiy(phone,code)){
            userService.updatePhone(phone,getLoginUser().getId());
        }else{
            throw  new ApiException(400,"请输入正确的短信验证码");
        }

    }

    /**
     *用户中心
     * 修改个人资料
     */
    @RequestMapping(value = "",method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @Auth
    public void update(@RequestBody User4Put put){
        userService.update(userId(),put);
    }


    /**
     * 登出
     * @param token
     */
    @RequestMapping(value = "loginout",method = RequestMethod.PUT)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @Auth
    public void loginOut(@RequestHeader(value = GloabConstant.tokenName) String token){
        userService.loginOut(token);
    }


    /**
     * 搜索用户
     * @return
     */
    @RequestMapping(value = "search",method = RequestMethod.POST)
    @Auth
    public PageDto<UserDto> search(@RequestBody UserSearch bean){
        handlerPage();
        Page<UserDto> res = userService.search(bean.getRoleIds(),bean.getDeptId(),bean.getName());
        return new PageDto<>(res) ;
    }



    /**
     * 删除用户
     * @param bean
     */
    @RequestMapping(value = "del",method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteUser(@RequestBody IdsBean bean){
        userService.deleteUsers(bean.getIds());
    }

    @RequestMapping(value = "{id}",method = RequestMethod.GET)
    public UserDto getOne(@PathVariable String id){
        UserDto user =  userService.getOne(id);
        List<String> roleIds = userService.findUserAllRoleId(id);
        user.setRoleIds(roleIds);
        return  user ;
    }

    /**
     * 获取所有部门
     * @return
     */
    @RequestMapping(value = "dept/all",method = RequestMethod.GET)
    public List<SysOrganization> deptAll(){
        return  userService.findAllDept();
    }

    @RequestMapping(value = "all",method = RequestMethod.GET)
    public List<UserDto> findAll(){
        return userService.findAllUser();
    }

    /**
     * 修改用户
     */
    @RequestMapping(value = "{id}",method = RequestMethod.PUT)
    public void update(@RequestBody UserDto user,@PathVariable String id){
        userService.updateUser(id,user);
    }

    @RequestMapping(value = "upload")
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String newName = UUID.randomUUID().toString() + suffixName;
        String filePath = path + "/" + newName;
        String imgUrl = url + "/" + newName;
        File dest = new File(filePath );
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            Map<String,String> res = new HashMap<>();
            res.put("url", e.getMessage());
        }
        Map<String,String> res = new HashMap<>();
        res.put("url",imgUrl);
        return  res ;
    }

    @RequestMapping(value = "synUser",method=RequestMethod.GET)
    @Auth
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void   synUser(@RequestHeader(value = GloabConstant.tokenName) String token){
         userService.synUser(1,1000,token);

    }


}
